package app.softtech.freechat.adapter;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import app.softtech.freechat.R;
import app.softtech.freechat.app.AppController;
import app.softtech.freechat.database.DatabaseUser;

import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;

public class UserListViewAdapter extends BaseAdapter{
	private Activity mActivity;
	private LayoutInflater mInflater;
	private List<DatabaseUser> mUserList;
	ImageLoader imageLoader = AppController.getInstance().getImageLoader();
	
	static final String TAG = CustomListViewAdapter.class.getSimpleName();
	
	
	public UserListViewAdapter(Activity activity, List<DatabaseUser> userList){
		this.mActivity = activity;
		this.mUserList = userList;
	}
	
	@Override
	public int getCount() {
		if(mUserList.size() == 0 ){
			return 1;
		}
		return mUserList.size();
	}

	@Override
	public Object getItem(int position) {
		return mUserList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if(mUserList.isEmpty()){
			//Return current convert view if user list is empty
			return convertView;
		}
		
		if(mInflater == null){
			//Initialized the inflater if null
			mInflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}
		
		if(convertView == null){
			//Initialized the convert view if null
			convertView = mInflater.inflate(R.layout.list_row, parent, false);
		}
		
		if(imageLoader == null){
			//Initialized the image loader if null
			imageLoader = AppController.getInstance().getImageLoader();
		}
		
		//Get attributes from layout
		NetworkImageView friendAvatar = (NetworkImageView) convertView.findViewById(R.id.img_avatar);
		TextView friendName = (TextView) convertView.findViewById(R.id.tv_friend_name);
		TextView friendEmail = (TextView) convertView.findViewById(R.id.tv_friend_status);
		
		//Get database of user by position
		DatabaseUser du = mUserList.get(position);
		
		//Add data to attributes
		friendAvatar.setImageUrl(du.getAvatar(), imageLoader);
		friendName.setText(du.getUserName());
		friendEmail.setText(du.getEmail());
		
		return convertView;
	}
}
